﻿using System;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Ink;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using GoogleServicesLib.GeoCoding;
using System.IO;
using Newtonsoft.Json;
using System.Threading;
using System.Threading.Tasks;

namespace GoogleServicesLib
{
    public static class GeocodingService
    {
        public static Uri ToUri(Uri relativeUri)
        {
            Uri baseUri = new Uri("http://maps.google.com/maps/api/geocode/");
            return new Uri(baseUri, relativeUri);
        }

        public async static Task<GeocodingResponse> GetResponse(GeocodingRequest request)
        {
            WebRequest webRequest = WebRequest.Create(ToUri(request.ToUri()));
            WebResponse webResponse = await webRequest.GetResponseAsync();

            using (StreamReader stream = new StreamReader(webResponse.GetResponseStream()))
            {
                JsonTextReader jReader = new JsonTextReader(stream);

                JsonSerializer serializer = new JsonSerializer();
                serializer.Converters.Add(new JsonEnumTypeConverter());
                return serializer.Deserialize<GeocodingResponse>(jReader);
            }
        }
    }
}
